package com.apes.autoparts.searcher.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.searcher.repository.AutopartsDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.mq.annotation.Consumer;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service("partsListService")

public class PartsListService extends DomainService {

    @Autowired
    AutopartsDao autopartsDao;


    private int publishI = 0;

    private int subscribeI = 0;

    /***
     * 拆分数据推送信息
     * menuName partChineseName epcVersion
     */
    public Map splitDataAndPublishMessageForTODO(SimpleRequest request) {
        JSONObject param = request.getJO();

        // 循环发送消息
        if (param.getString("partChineseName") != null) {
            JSONArray partChineseNames = JSONArray.parseArray(param.getString("partChineseName"));
            for (int i = 0, len = partChineseNames.size(); i < len; i++) {
                MQUtil.publish("autoparts.searchPartsForDataCenterDailyResolve", "数据中心配件解析",
                        MapUtil.mapper("userId", param.getString("userId"), "menuName", param.getString("menuName"), "epcVersion", param.getString("epcVersion"),
                                "partChineseName", partChineseNames.getString(i)));
            }
        }

        System.out.print("推送消息次数：" + this.publishI++);

        return MapUtil.mapper("message", "调用成功");
    }


    public Map splitDataAndPublishMessageForParseSign(SimpleRequest request) {
        JSONObject param = request.getJO();

        // 循环发送消息
        if (param.getString("partChineseName") != null) {
            JSONArray partChineseNames = JSONArray.parseArray(param.getString("partChineseName"));
            for (int i = 0, len = partChineseNames.size(); i < len; i++) {
                MQUtil.publish("autoparts.updateParseSign", "更新配件编译标记",
                        MapUtil.mapper("userId", param.getString("userId"), "userName", param.getString("userName"), "menuName", param.getString("menuName"), "epcVersion", param.getString("epcVersion"),
                                "partChineseName", partChineseNames.getString(i), "parseSign", param.getInteger("parseSign")));
            }
        }
        return MapUtil.mapper("message", "调用成功");

    }

    /***
     * 通过 epcVersion menuId menuName parChineseName 查询所有的满足条件的配件并做去重
     */

    @Consumer(topic = "autoparts.searchPartsForDataCenterDailyResolve")
    public void searchPartsForDataCenterDailyResolve(SimpleRequest request) {

        System.out.print("执行消息次数：" + this.subscribeI++);


        JSONObject param = request.getJO();
        JSONObject returnJson = new JSONObject();
        JSONArray cacheArray = new JSONArray();
        JSONArray partsList = autopartsDao.searchPartsForDataCenterDailyResolve(param);


        if (partsList != null && partsList.size() > 0) {
            // 进行 partNumber分组

            Map<String, List<Object>> groupByPartNumber = partsList.stream().collect(Collectors.groupingBy(json -> {
                JSONObject jsonObject = (JSONObject) json;
                return jsonObject.getString("PARTNUMBER") != null ? jsonObject.getString("PARTNUMBER") : "";
            }));

            groupByPartNumber.keySet().forEach(partNumber -> {
                Map<String, List<Object>> groupByPartNumberAndSvn = groupByPartNumber.get(partNumber).stream().collect(Collectors.groupingBy(json -> {
                    JSONObject jsonObject = (JSONObject) json;
                    return jsonObject.getString("PNC") != null ? jsonObject.getString("PNC") : "";
                }));
                groupByPartNumberAndSvn.keySet().forEach(svn -> {
                    JSONArray objectList = groupByPartNumberAndSvn.get(svn).stream().sorted(((o1, o2) -> {
                        if( ((JSONObject) o1).getString("IMGNAME") == null ) return -1;
                        if( ((JSONObject) o2).getString("IMGNAME") == null ) return 1;
                        return ((JSONObject) o1).getString("IMGNAME").compareTo(((JSONObject) o2).getString("IMGNAME"));
                    })).collect(Collectors.toCollection(JSONArray::new));

                    JSONObject tempJson = new JSONObject();
                    List<String> list = new ArrayList();
                    IntStream.range(0, objectList.size()).forEach(i -> {
                        JSONObject orderJson = objectList.getJSONObject(i);
                        if (i == 0) {
                            tempJson.put("imgOrder", orderJson.getString("IMGNAME"));
                            tempJson.put("description", orderJson.getString("OEMS"));
                            tempJson.put("partDescription", orderJson.getString("PJMC"));
                            tempJson.put("svn", svn);
                            tempJson.put("partNumber", partNumber);
                            tempJson.put("ts01", orderJson.getString("TS01"));
                        }
                        if (list.size() < 12) list.add(orderJson.getString("IMGNAME"));
                    });
                    tempJson.put("imgName", String.join(";", list));

                    // 写入精友配件名称 + 外部渠道名称
                    JSONObject thirdPartyPartDescription = autopartsDao.searchThirdPartyPartDescription(tempJson);
                    if( !thirdPartyPartDescription.isEmpty() ){
                        tempJson.put("partDescriptionJingyou", thirdPartyPartDescription.getString("PARTDESCRIPTIONJINGYOU"));
                        tempJson.put("partDescriptionExt", thirdPartyPartDescription.getString("PARTDESCRIPTIONEXT"));
                    }

                    cacheArray.add(tempJson);

                });
            });
        }

        returnJson.putAll(MapUtil.mapper("userId", param.getString("userId"), "menuName", param.getString("menuName"), "partChineseName",
                param.getString("partChineseName"), "epcVersion", param.getString("epcVersion")));
        returnJson.put("epcPartNumberParseList", cacheArray);

        /***
         * 回调原始数据接口保存数据
         */
        invoke("autoparts.epcPartNumberParse.create", returnJson);
    }


    /***
     * 更新编译标记
     * 0： 删除所有已编译的数据，新增一条空数据
     * 1： 更新所有编译标记为1
     */

    @Consumer(topic = "autoparts.updateParseSign")
    public void updateParseSign(SimpleRequest request) {
        JSONObject param = request.getJO();

        // 不编译
        if (param.getIntValue("parseSign") == 0) {
            JSONArray partsList = autopartsDao.searchPartNumberForParseSign(param);
            if (partsList != null && partsList.size() > 0) {
                for (int i = 0, len = partsList.size(); i < len; i++) {
                    String partNumber = partsList.getJSONObject(i).getString("PARTNUMBER");
                    if (partNumber != null) {
                        // 先删除再写入
                        autopartsDao.deleteParseData(new JSONObject(MapUtil.mapper("epcVersion", param.getString("epcVersion"),
                                "partNumber", partNumber)));
                        autopartsDao.insertParseData(new JSONObject(MapUtil.mapper("EPC_BBMC", param.getString("epcVersion"),
                                "PARTNUMBER", partNumber,
                                "PJMCID", null, "PJMC", null, "LRR", param.getString("userName"), "TS01",
                                DateUtil.format(new Date(), "yyyyMMdd.HHmmss.SSS"), "BYBJ", 0)));

                    }
                }
            }
        } else if (param.getIntValue("parseSign") == 1){
            // 编译
            param.put("TS01", DateUtil.format(new Date(), "yyyyMMdd.HHmmss.SSS"));
            autopartsDao.updateParseSignToTrue(param);
        }
    }

    /***
     * 通过配件信息查询所有的oe信息
     */

    public JSONObject searchPartParse(SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONObject returnJson = new JSONObject();
        JSONArray cacheArray = new JSONArray();
        JSONObject tempJson;
        JSONArray partsParseList = autopartsDao.searchPartParse(param);

        for (int i = 0, len = partsParseList.size(); i < len; i++) {
            tempJson = partsParseList.getJSONObject(i);
            cacheArray.add(this.invoke("autoparts.partsListConvert", tempJson));
        }

        returnJson.put("data", cacheArray);
        return returnJson;
    }


}
